package com.svse.controller;

import com.svse.entity.EmpEntity;
import com.svse.util.IPUtils;
import com.svse.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author LiYuhang
 * @version 0.1
 * @application 字段效验demo
 * @Copyright 上海危网信息科技有限公司版权所有
 * @company wwsoft
 * @time 2019/9/4 8:29
 */

@RestController
@RequestMapping("/empEntity")
public class EmpController {
    private static Logger logger = LoggerFactory.getLogger(EmpController.class);
    @Autowired
    private RedisUtil redisService;


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Map<String, Object> save(@RequestBody @Valid EmpEntity empEntity, BindingResult result) {
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String, Object> errorMap = new HashMap<>(10);
        fieldErrors.forEach(error -> {
                    logger.error("字段: {} 校验失败, Message:{} \n", error.getField(), error.getDefaultMessage());
                    errorMap.put(error.getField(), error.getDefaultMessage());
                }
        );
        empEntity.setBirthday(new Date());
        errorMap.put("empEntity", empEntity);
        return errorMap;

    }

    @RequestMapping(value = "/getIp", method = RequestMethod.POST)
    public String getIp(HttpServletRequest request) {
        //获取访问IP
        String ip = IPUtils.getIpAddr(request);
        logger.info("访问IP地址是:{} \n" , ip);
        return ip;
    }
}
